Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var gulp = require('gulp'),
    useref = require('gulp-useref'),
    minifyCss = require('gulp-minify-css'),
    runSequence = require('run-sequence'),
    uglify = require('gulp-uglify'),
    clean = require('gulp-clean'),
    rev = require('gulp-rev'),
    revReplace = require('gulp-rev-replace'),
    revCollector = require('gulp-rev-collector'),
    rename = require("gulp-rename"),
    replace = require('gulp-replace'),
    babel = require("gulp-babel"),
    htmlmin = require('gulp-htmlmin'),
    zip = require('gulp-zip'),
    sourcemaps = require('gulp-sourcemaps'),
    autoprefixer = require('gulp-autoprefixer'),
    gulpif = require('gulp-if');

let dir = 'D:/PICC'
let zipFileName = `PICC-WEB-${new Date().Format("yyyyMMdd-hhmm")}.zip`;


let fs = require('fs'),
    path = require('path'),
    exec = require('child_process').exec;


var config = {
    name: 'PICC-WEB',
    version: 'v1.0.0',
    oss: `http://image.fcyun.com/PICCWEB/`,
    replaceFileArr: [],
    projSrc: ``
};

gulp.task('_clean', done => {
    return gulp.src('dist', {
        read: false
    }).pipe(clean());
});

gulp.task('_zip', done => {
    return gulp.src('./dist/**/*.*')
        .pipe(zip(zipFileName))
        .pipe(gulp.dest(dir))
})

gulp.task('_open', done => {
    console.log(`编译完成:${dir}/${zipFileName}`)
    var child = exec('explorer d:\\PICC', (error, stdout, stderr) => {
        done();
    });
})

gulp.task('_move_plugins', done => {
    return gulp.src('./static/plugins/**/*.js')
        .pipe(gulp.dest('./dist/static/plugins'))
});


gulp.task('_rev_js', ['_move_plugins'], done => {
    return gulp.src('./static/**/*.js')
        .pipe(rev())
        .pipe(gulp.dest('./dist/static/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./dist/rev/js/'));
});

gulp.task('_rev_static', done => {
    return gulp.src(['./static/**/*.gif', './static/**/*.jpg', './static/**/*.png', './static/**/*.svg', './static/**/*.eot', './static/**/*.woff2', './static/**/*.woff', './static/**/*.ttf'])
        .pipe(rev())
        .pipe(gulp.dest('./dist/static'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./dist/rev/img'))
})

gulp.task('_move_fonts', done => {
    return gulp.src('./static/fonts/iconfont/*.*')
        .pipe(gulp.dest('./dist/build/v1.0.0/'))
})
gulp.task('_rev_css', ['_rev_static', '_move_fonts'], done => {
    return gulp.src(['./dist/rev/**/*.json', './static/**/*.css'])
        .pipe(revCollector())
        .pipe(rev())
        .pipe(gulp.dest('./dist/static/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./dist/rev/css/'));
})

gulp.task('_move_workshop', function (done) {
    return gulp.src(['./workshop/*.html'])
        .pipe(rename(path => {
            path.basename = 'workshop'
        }))
        .pipe(gulp.dest('./dist/'));
});
gulp.task('_move_html', ['_move_workshop'], function (done) {
    return gulp.src(['*.html'])
        .pipe(gulp.dest('./dist/'));
});


gulp.task('_html', function (done) {
    return gulp.src(['./dist/rev/**/*.json', './dist/*.html', './pages/**/*.html'])
        .pipe(revCollector())
        .pipe(useref())
        .pipe(rev())
        .pipe(revReplace({
            modifyReved: (filename => {
                if (filename.indexOf('.html') > -1) {
                    var src = `./dist/${filename}`;
                    if (config.replaceFileArr.indexOf(src) == -1) {
                        config.replaceFileArr.push(src);
                    }
                } else if (filename.indexOf('.css') > -1 || filename.indexOf('.js') > -1) {
                }

                return filename
            })
        }))
        .pipe(rename(path => {
            if (path.extname === '.html') {
                if (path.dirname === '.' && path.basename.indexOf('workshop') > -1) {
                    //workshop.html
                    path.dirname = './workshop/';
                    path.basename = 'index';
                } else if (path.dirname === '.' && path.basename.indexOf('index') > -1) {
                    //login.html
                    path.basename = path.basename.replace(/\-\w+$/, '');
                } else {
                    path.dirname = 'pages/' + path.dirname;
                }
            }
        }))
        // .pipe(gulpif('*.js', sourcemaps.init()))
        .pipe(gulpif('*.html', replace(/\.\/build/g, str => {
            return '/build';
        })))
        .pipe(gulpif('*.css', autoprefixer({
            browsers: ['last 10 versions'],
            cascade: true,
            remove: true
        })))
        .pipe(gulpif('*.css', minifyCss()))
        .pipe(gulpif('*.js', babel({
            presets: ['es2015']
        })))
        .pipe(gulpif('*.js', uglify().on('error', function (err) {
            console.log('===============================================')
            console.error(err);
            console.log('===============================================')
            this.emit('end');
        })))
        // .pipe(gulpif('*.js', sourcemaps.write('.')))
        .pipe(gulp.dest('./dist/'))
});

gulp.task('_workshop', done => {
    return gulp.src('./dist/workshop/*.html')
        .pipe(rename(path => {
            if (path.basename.indexOf('index') > -1) {
                path.basename = 'workshop'
            }
        }))
        .pipe(gulp.dest('./dist/'));
})

/**
 * 压缩业务逻辑js
 */
gulp.task('_jsmin', function (done) {
    return gulp.src('./dist/static/modules/**/*.js')
        // .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(uglify().on('error', function (err) {
            console.log(err);
            this.emit('end');
        }))
        // .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist/static/modules/'))
});

gulp.task('_htmlmin', function (done) {
    return gulp.src(path.resolve(config.projSrc, './dist/**/*.html'))
        .pipe(htmlmin({
            removeComments: true, //清除HTML注释
            collapseWhitespace: true, //压缩HTML
            collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
            removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
            removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
            removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
            minifyJS: true, //压缩页面JS
            minifyCSS: true //压缩页面CSS
        }))
        .pipe(gulp.dest(path.resolve(config.projSrc, './dist/')))
});

gulp.task('main', done => {
    // return runSequence(['_clean'], ['_move_html'], ['_rev_js', '_rev_css'], ['_html'], ['_workshop'], ['_jsmin'], done)
    return runSequence(['_clean'], ['_move_html'], ['_rev_js', '_rev_css'], ['_html'], ['_jsmin', '_htmlmin'], ['_workshop'], ['_zip'], ['_open', '_clean'], done)
})